<template>
  <div>
    <div style="float:right;">
      <el-button type="success" style="padding:13px 20px;" @click="add">添加新教师</el-button>
    </div>
    <div class="allsearch">
      <section class="search-content">
        <el-row :gutter="4" type="flex" justify="start">
          <el-col :span="24">
            <el-input v-model="listQuery.nickName" style="width:200px;" placeholder="用户名" @keyup.enter.native="handleFilter"/>
            <el-button type="primary" size="medium" @click="handleFilter">搜索</el-button>
            <el-button size="medium" type="info" @click="clearParams">清空</el-button>
          </el-col>
        </el-row>
      </section>
    </div>

    <el-table :data="teacherManageList" border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column min-width="10%" align="center" label="用户名">
        <template slot-scope="scope">
          <span>{{ scope.row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="姓名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="推荐老师">
        <template slot-scope="scope">
          <span>{{ scope.row.promoted === 0 ? '否' : '是' }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="最近登录">
        <template slot-scope="scope">
          <span>{{ scope.row.loginTime }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="15%" align="center" label="查看记录">
        <template slot-scope="scope">
          <el-dropdown
            split-button
            type="primary"
            @click="showTeacher(scope.row, true)"
            @command="handleCommand($event,scope)"
          >查看
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.promoted === 0" command="1">推荐</el-dropdown-item>
              <el-dropdown-item v-if="scope.row.promoted === 1" command="2">取消推荐</el-dropdown-item>
              <el-dropdown-item command="3">编辑</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"/>

    <!-- 添加新教师 -->
    <el-dialog :visible.sync="dialog.addUser" :before-close="cannel" :title="dialog.view ? '查看教师' : dialog.edit ? '编辑教师' : '创建新教师'" width="700px">
      <el-form ref="addUserForm" :model="dialogData.addUser" :rules="rules">
        <el-form-item :label-width="formLabelWidth" label="邮箱" prop="email">
          <el-input :disabled="dialog.view || dialog.edit" v-model="dialogData.addUser.email" style="width:450px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="账号" prop="account">
          <el-input :disabled="dialog.view || dialog.edit" v-model="dialogData.addUser.account" style="width:450px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="姓名" prop="name">
          <el-input :disabled="dialog.view" v-model="dialogData.addUser.name" style="width:450px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="用户名" prop="nickName">
          <el-input :disabled="dialog.view || dialog.edit" v-model="dialogData.addUser.nickName" style="width:450px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="手机号" prop="verifiedMobile">
          <el-input :disabled="dialog.view" v-model="dialogData.addUser.verifiedMobile" style="width:450px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="密码" prop="password">
          <el-input :disabled="dialog.view" v-model="dialogData.addUser.password" style="width:450px;"/>
        </el-form-item>
        <el-form-item v-if="!dialog.view" :label-width="formLabelWidth" label="确认密码" prop="confirmPassword">
          <el-input v-model="dialogData.addUser.confirmPassword" style="width:450px;"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="用户权限" prop="roleIds">
          <el-checkbox :disabled="dialog.view" v-model="dialogData.addUser.roleIds" :label="role.id" :key="role.id">{{ role.name }}</el-checkbox>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="详细信息">
          <div style="width:450px;">
            <tinymce :height="200" :show="true" v-model="dialogData.addUser.description"/>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cannel">取 消</el-button>
        <el-button v-if="!dialog.view" type="primary" @click="addTeacher()">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialog.addMoreUser" title="设置推荐教师" width="580px">
      <el-form :model="dialogData.addMoreUser" :rules="rules" ref="moreUserForm">
        <el-form-item :label-width="formLabelWidth" label="序号" prop="number">
          <el-input v-model="dialogData.addMoreUser.number" style="width:300px;"/>
          <p style="margin:0;">请输入长度不能超过8位的整数</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddMoreUserDialog">取 消</el-button>
        <el-button type="primary" @click="promotedTeacher()">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // 分页组件
  import Tinymce from '@/components/Tinymce'
  import {getBranchCampusId, getBranchCampusName, getTenantId, getUserId, getUserName} from '@/utils/auth'
  import {getEduxcloudTeacherPager, getEduxcloudUserById, getEduxcloudUserDic, saveOrUpdateEduxcloudUser, updateEducloudTeacherPromoted} from '@/api/user/user' // 数据接口

  export default {
    components: { Tinymce,Pagination},
    data() {
      const confirmPassword = (rule, value, callback) => {
        if (!this.dialogData.addUser.password) {
          callback(new Error('请先输入密码再进行确认'))
        } else if (!value) {
          callback(new Error('请输入确认密码'))
        } else {
          if (value !== this.dialogData.addUser.password) {
            callback(new Error('输入的密码不一致，请重新输入'))
          } else {
            callback()
          }
        }
      };
      return {
        role: '',
        teacherManageList: null,
        formLabelWidth: '100px',
        total: 0,
        listLoading: true,
        listQuery: {
          nickName: '',
          tenantId: getTenantId(),
          page: 1,
          limit: 20
        },
        dialog: {
          addUser: false,
          edit: false,
          view: false,
          addMoreUser: false
        },
        dialogData: {
          addUser: {roleIds: []},
          addMoreUser: {
            teacherId: '',
            number: ''
          },
          view: {}
        },
        rules: {
          email: [
            {required: true, message: '请输入邮箱地址', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          account: [
            {required: true, message: '请输入账号', trigger: 'blur'}
          ],
          nickName: [
            {required: true, message: '请输入用户昵称', trigger: 'blur'}
          ],
          verifiedMobile: [
            {required: true, message: '请输入手机号码', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          roleIds: [
            {required: true, message: '请选择权限', trigger: 'blur'}
          ],
          confirmPassword: [
            {validator: confirmPassword, trigger: 'blur'},
            {required: true, message: '请输入确认密码', trigger: 'blur'}
          ],
          number: [
            {required: true, message: '必填信息', trigger: 'blur'},
            {min: 1, max: 8, message: '长度不能超过8位', trigger: 'blur'},
            {pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入长度不能超过8位的整数'}
          ]
        }
      }
    },
    created() {
      this.getTeacherManageListData();
      this.initUserDic()
    },
    methods: {
      // 改变分页页数
      handleSizeChange(val) {
        this.listQuery.page = 1;
        this.listQuery.limit = val.value;
        this.getTeacherManageListData()
      },
      // 改变当前页
      handleCurrentChange(val) {
        this.listQuery.page = val.value;
        this.getTeacherManageListData()
      },
      // 接口获取数据
      getTeacherManageListData() {
        getEduxcloudTeacherPager(this.listQuery).then(response => {
          this.teacherManageList = response.data.items;
          this.total = response.data.total
        })
      },
      initUserDic() {
        getEduxcloudUserDic(getTenantId()).then(response => {
          const roleList = response.data.roleList;
          for (const item in roleList) {
            if (roleList[item].name === '教师') {
              this.role = roleList[item]
            }
          }
        })
      },
      // 数据检索
      handleFilter() {
        this.getTeacherManageListData()
      },
      add() {
        this.dialog.addUser = true;
        this.dialog.view = false;
        this.dialog.edit = false;
        this.dialogData.addUser = {};
      },
      cannel() {
        this.dialog.addUser = false;
        this.dialog.view = false;
        this.dialog.edit = false;
        this.dialogData.addUser = {roleIds: []};
        this.$refs['addUserForm'].resetFields();
      },
      clearParams() {
        this.listQuery.nickName = '';
        this.getTeacherManageListData()
      },
      showTeacher(teacher) {
        this.dialog.addUser = true;
        this.dialog.view = true;
        getEduxcloudUserById(teacher.id).then(res => {
          this.dialogData.addUser = res.data.eduxcloudUser;
          this.dialogData.addUser.roleIds = this.dialogData.addUser.roleIds.split(',');
          this.dialogData.addUser.confirmPassword = this.dialogData.addUser.password
        })
      },
      editTeacher(teacher) {
        this.dialog.addUser = true;
        this.dialog.edit = true;
        this.dialog.view = false;
        getEduxcloudUserById(teacher.id).then(res => {
          this.dialogData.addUser = res.data.eduxcloudUser;
          this.dialogData.addUser.roleIds = this.dialogData.addUser.roleIds.split(',');
          this.dialogData.addUser.confirmPassword = this.dialogData.addUser.password
        })
      },
      handleCommand(command, scope) {
        if (command === '1') {
          this.recommend(scope.row)
        } else if (command === '2') {
          this.cancelRecommend(scope.row)
        } else if (command === '3') {
          this.editTeacher(scope.row)
        }
      },
      recommend(row) {
        this.dialog.addMoreUser = true;
        this.dialogData.addMoreUser.teacherId = row.id
      },
      promotedTeacher() {
        this.$refs.moreUserForm.validate((valid) => {
          if (valid) {
            this.dialog.addMoreUser = false;
            const teacherPromoted = {'id': this.dialogData.addMoreUser.teacherId, 'promoted': '1', 'promotedSeq': this.dialogData.addMoreUser.number};
            updateEducloudTeacherPromoted(teacherPromoted).then(() => {
              this.dialogData.addMoreUser = {};
              this.$notify({title: '成功', message: '教师推荐成功', type: 'success', duration: 2000});
              this.getTeacherManageListData()
            })
          } else {
            return false
          }
        })
      },
      cancelRecommend(teacher) {
        this.$confirm(`确定取消推荐吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const teacherPromoted = {'id': teacher.id, 'promoted': '0', 'promotedSeq': '0'};
          updateEducloudTeacherPromoted(teacherPromoted).then(() => {
            this.dialogData.addMoreUser.number = '';
            this.$notify({title: '成功', message: '取消推荐成功', type: 'success', duration: 2000});
            this.getTeacherManageListData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '放弃取消'
          })
        })
      },
      cancelAddMoreUserDialog() {
        this.dialog.addMoreUser = false;
        this.dialogData.addMoreUser = {}
      },
      addTeacher() {
        this.$refs['addUserForm'].validate((valid) => {
          if (valid) {
            if (!this.dialogData.addUser.id) {
              this.dialogData.addUser.userType = 'TEACHER';
              this.dialogData.addUser.creatorId = getUserId();
              this.dialogData.addUser.creatorName = getUserName();
              this.dialogData.addUser.tenantId = getTenantId();
              if (getBranchCampusId()) {
                this.dialogData.addUser.branchCampusId = getBranchCampusId();
                this.dialogData.addUser.branchCampusName = getBranchCampusName()
              }
            }
            this.dialogData.addUser.roleIds = this.dialogData.addUser.roleIds[0];
            saveOrUpdateEduxcloudUser(this.dialogData.addUser).then(() => {
              this.dialogData.addUser = {};
              this.$notify({title: '成功', message: '成功', type: 'success', duration: 2000});
              this.getTeacherManageListData();
              this.$refs['addUserForm'].resetFields()
            });
            this.dialog.addUser = false;
            if (this.dialog.view) this.dialog.view = false;
            if (this.dialog.edit) this.dialog.edit = false
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .allsearch {
    margin-top: 0;
    padding: 0;

    .search-content {
      width: 100%;
    }
  }
</style>
